﻿#region <<版本注释>>
/*---------------------------------------------------------------------
* 项目名称：DoubleDB
* 项目描述：
* 类 名 称：DataCtrl
* 类 描 述：
* 所在的域：DESKTOP-6CB1TV7
* 命名空间：DoubleDB
* 机器名称：DESKTOP-6CB1TV7
* CLR 版本：4.0.30319.42000
* 作    者：wky
* 创建时间：2023/01/03 19:09:58
* 更新时间：2023/01/03 19:09:58
* 版 本 号:V1.0.0
***********************************************************************
* Copyright @ wky 2023. All rights reserved.
***********************************************************************
//-------------------------------------------------------------------*/
#endregion

using DoubleDB.DBVisit;
using DoubleDB.IotNiRenDataStruct;
using DoubleDB.NiRenDataStruct;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DoubleDB
{
    public class DataCtrl
    {

        public static List<Timing> timings = new List<Timing>();

        /// <summary>
        /// 读旧库的定时数据
        /// </summary>
        public static void readOldDataBaseAllTimeingData() {
            //CMysqlHelper.ExecuteNonQuery(CMysqlHelper.iotNirenConnStr, System.Data.CommandType.Text, "select * from timing", null);
            using (MySqlDataReader reader = CMysqlHelper.ExecuteReader(CMysqlHelper.iotNirenConnStr, CommandType.Text, "select * from timing", null)) {

                while (reader.Read())
                {
                    Timing timing = new Timing() {
                        Id = CMysqlHelper.toInt32(reader, "id"),
                        Type = CMysqlHelper.toString(reader,"type"),
                        Dev = CMysqlHelper.toString(reader,"dev"),
                        Etim = CMysqlHelper.toString(reader,"etim"),
                        Sta = CMysqlHelper.toString(reader,"sta"),
                        Wed = CMysqlHelper.toString(reader,"wed"),
                        Tim = CMysqlHelper.toString(reader,"tim"),
                        Order = CMysqlHelper.toString(reader,"order"),
                        Utim = CMysqlHelper.toString(reader,"utim"),
                        LongTime = CMysqlHelper.toString(reader,"longtime"),
                        Stim = CMysqlHelper.toString(reader,"stim"),
                        Dat = CMysqlHelper.toString(reader,"dat"),
                        Dat1 = CMysqlHelper.toString(reader,"dat1"),
                        Tb = CMysqlHelper.toString(reader,"tb"),
                        TbSta = CMysqlHelper.toString(reader,"tbsta"),
                        Comtim = CMysqlHelper.toString(reader,"comtim")
                    };

                    timings.Add(timing);

                }
            }
        }

        public static List<DoTable> dos = new List<DoTable>();
        /// <summary>
        /// 读旧表的do数据
        /// </summary>
        public static void readDoTableData() {
            using(MySqlDataReader reader = CMysqlHelper.ExecuteReader(CMysqlHelper.iotNirenConnStr,CommandType.Text, "select * from `do`", null)) {
                while (reader.Read()) {
                    DoTable doTable = new DoTable() {
                        Id = CMysqlHelper.toInt32(reader,"id"),
                        Uid = CMysqlHelper.toString(reader,"uid"),
                        No = CMysqlHelper.toInt32(reader,"no")
                    };

                    dos.Add(doTable);
                }
            }
        }

        public static List<SysDeviceInfo> devs = new List<SysDeviceInfo>();
        /// <summary>
        /// 读取新数据库所有设备信息
        /// </summary>
        public static void readNewDataBaseAllDeviceInfos() {
            using (MySqlDataReader reader = CMysqlHelper.ExecuteReader(CMysqlHelper.nirenConnStr,CommandType.Text,"select * from SysDeviceInfo",null)) {
                while (reader.Read()) {
                    SysDeviceInfo dev = new SysDeviceInfo() {
                        Id = CMysqlHelper.toInt32(reader,"id"),
                        DevName = CMysqlHelper.toString(reader,"devName"),
                        DevSn = CMysqlHelper.toString(reader,"devSn"),
                        UserId = CMysqlHelper.toInt32(reader,"userId"),
                        DoNum = CMysqlHelper.toInt32(reader,"doNum"),
                        DiNum = CMysqlHelper.toInt32(reader,"diNum")
                    };

                    devs.Add(dev);
                }
            }
        }

        public static List<SysDeviceManage> nodes = new List<SysDeviceManage>();
        /// <summary>
        /// 读取新数据库所有节点信息
        /// </summary>
        public static void readNewDataBaseAllNodeInfos() {
            using (MySqlDataReader reader = CMysqlHelper.ExecuteReader(CMysqlHelper.nirenConnStr, CommandType.Text, "select * from SysDeviceManage", null)) {
                while (reader.Read()) {
                    SysDeviceManage node = new SysDeviceManage()
                    {
                        Id = CMysqlHelper.toInt32(reader, "id"),
                        NodeName = CMysqlHelper.toString(reader,"nodeName"),
                        NodeType = CMysqlHelper.toInt32(reader,"nodeType"),
                        NodeCh = CMysqlHelper.toInt32(reader,"nodeCh"),
                        DevSn = CMysqlHelper.toString(reader,"devSn")
                    };

                    nodes.Add(node);
                }
            }
        }

        public static List<SysTimeTrigger> timers = new List<SysTimeTrigger>();
        /// <summary>
        /// 数据转换
        /// </summary>
        public static void dataConvert() {
            DateTime startDt = DateTime.Now;
            readOldDataBaseAllTimeingData();
            readDoTableData();
            readNewDataBaseAllDeviceInfos();
            readNewDataBaseAllNodeInfos();
            long mSec = DataConvert.calcDateTime2Msec(DateTime.Now, startDt);
            Console.WriteLine("初始化总用时: " + mSec + " ms");

            int successCount = 0;
            int failureCount = 0;
            int discardCount = 0;
            int noSubtaskCount = 0;
            int noUserCount = 0;
            int unsynchronizedCount1 = 0;
            int unsynchronizedCount2 = 0;

            //int delCount = 0;
            List<int> oldTaskIds = new List<int>();

            startDt = DateTime.Now;
            foreach (var timing in timings) {

                /*if (timing) {
                    delCount++;
                    continue;
                }*/

                if (timing.Dat1 == null || timing.Dat1.Equals(""))
                {
                    discardCount++;
                    continue;
                }

                //if (timing.Tb.Contains("未同步") && timing.Wed.Contains("星期") && timing.Tim.Contains("-")) {
                if (timing.Wed.Contains("星期") && timing.Tim.Contains("-")) {
                    Console.WriteLine("旧任务Id为:{0}",timing.Id);
                    unsynchronizedCount1++;
                    continue;
                }

                //if (timing.Tb.Contains("未同步") && timing.Wed.Contains("单次") && timing.Tim.Contains("时"))
                if (timing.Wed.Contains("单次") && timing.Tim.Contains("时"))
                {
                    Console.WriteLine("旧任务Id为:{0}", timing.Id);
                    unsynchronizedCount2++;
                    continue;
                }

                DataConvert dataConvert = new DataConvert(timing);

                var devInfos = devs.Where(o => o.Id == dataConvert.devConvert()).ToList();
                int userId = 0;
                if (devInfos.Count == 0) {
                    noUserCount++;
                    continue;
                }
                userId = devInfos[0].UserId;
                if (userId == 0) {
                    noUserCount++;
                    continue;
                }

                int workMode = dataConvert.workMode();
                if (workMode == 0) {
                    discardCount++;
                    continue;
                }
                

                SysTimeTrigger timeTrigger = new SysTimeTrigger()
                {
                    UserId = userId,
                    IsEnabled = dataConvert.staConvert(),
                    TimerName = dataConvert.timerName(),
                    StarTime = dataConvert.stimConvert(),
                    EndTime = dataConvert.etimConvert(),
                    ExeTime = dataConvert.timConvert(),
                    WorkMode = dataConvert.workMode(),
                    AWeekFlag = dataConvert.wedConvert(),
                    AmonthFlag = 0,
                    SyncState = dataConvert.getSyncState(),//删除即为3(DelSync)，其他均为0
                    SysOpt = "Admin",
                    CreateDate = DateTime.Now,
                    ModifyDate = dataConvert.utimConvert(),
                    Remark = "data convert",
                    Events = dataConvert.dat1Convert()
                };

                if (timeTrigger.Events.Count == 0) {
                    noSubtaskCount++;
                    oldTaskIds.Add(timing.Id);
                }

                if (saveTimerInfo(timeTrigger)){
                    successCount++;
                } else {
                    failureCount++;
                }
            }
            mSec = DataConvert.calcDateTime2Msec(DateTime.Now, startDt);
            Console.WriteLine("数据转换总用时: " + mSec + " ms");

            Console.WriteLine("总定时任务数:{0},写入成功数量:{1},写入失败数量:{2},无效数据数量:{3},无子项数据量:{4},无用户任务数量:{5},未同步错误任务数1:{6},未同步错误任务数2:{7}",
                timings.Count,successCount,failureCount,discardCount,noSubtaskCount, noUserCount, unsynchronizedCount1, unsynchronizedCount2);
            /*Console.WriteLine("现在将无子项旧任务的id写入文件:");
            string txt = "";
            foreach (var oldTaskId in oldTaskIds) {
                if (!txt.Equals(""))
                    txt += "\r\n";
                txt += oldTaskId.ToString();
            }

            writeFile("C:\\t.txt",txt);
            Console.WriteLine("数据写入完成!");*/
        }

        public static void writeFile(string path, string txt) {
                FileStream fs = new FileStream(path, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                sw.Write(txt);
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
        }

        public static bool saveTimerInfo(SysTimeTrigger time) {


            if (time == null) return false;
            string sql = "insert into SysTimeTrigger(userId,isEnabled,timerName,StartTime,EndTime,ExeTime,WorkMode,AWeekFlag,AmonthFlag,syncState,SysOpt,CreateDate,ModifyDate,Remark)" 
                + " values(" + time.UserId.ToString() + "," + time.IsEnabled.ToString() + ",'" + time.TimerName + "','" + time.StarTime.ToString(DataConvert.dtFormatStr) + "','" 
                + time.EndTime.ToString(DataConvert.dtFormatStr) + "','" + time.ExeTime.ToString(DataConvert.dtFormatStr) + "',"
                + time.WorkMode.ToString() + "," + time.AWeekFlag.ToString() + "," + time.AmonthFlag.ToString() + "," + time.SyncState.ToString() + ",'" + time.SysOpt + "','" 
                + time.CreateDate.ToString(DataConvert.dtFormatStr) + "','" + time.ModifyDate.ToString(DataConvert.dtFormatStr) + "','" + time.Remark + "')";

            int result = CMysqlHelper.ExecuteNonQuery(CMysqlHelper.nirenConnStr, CommandType.Text, sql, null);
            if (result == 0) {
                Console.WriteLine("定时信息保存失败!");
                Console.WriteLine("执行失败的SQL为:" + sql);
                return false;
            }

            int taskId = 0;
            sql = "select id from SysTimeTrigger where timerName='" + time.TimerName + "'";
            using (MySqlDataReader reader = CMysqlHelper.ExecuteReader(CMysqlHelper.nirenConnStr, CommandType.Text, sql,null)) {
                while (reader.Read()) {
                    taskId = CMysqlHelper.toInt32(reader, "id");
                }
            }

            foreach (var te in time.Events) {
                te.TaskId = taskId;
                te.TaskType = 0;

                sql = "insert into SysTaskCtrlEvent(taskType,taskId,areaIds,areaNames,devIds,devNames,nodeIds,nodeNames,actionType,flushTime,closeTime,loopNum,dlyTime,syncState,createDate,modifyDate)" 
                    + " values(" + te.TaskType.ToString() + "," + te.TaskId.ToString() + ",'" + te.AreaIds + "','" + te.AreaNames + "','" + te.DevIds + "','" + te.DevNames + "','" + te.NodeIds + "','" 
                    + te.NodeNames + "'," + te.ActionType.ToString() + "," + te.FlushTime.ToString() + "," + te.CloseTime.ToString() + "," + te.LoopNum.ToString() + "," + te.DlyTime.ToString() + "," 
                    + te.SyncState.ToString() + ",'" + te.CreateDate.ToString(DataConvert.dtFormatStr) + "','" + te.ModifyDate.ToString(DataConvert.dtFormatStr) + "')";

                result = CMysqlHelper.ExecuteNonQuery(CMysqlHelper.nirenConnStr, CommandType.Text, sql, null);
                if (result == 0) {
                    Console.WriteLine("保存定时信息的任务事件失败");
                    Console.WriteLine("执行失败的SQL为:" + sql);
                    return false;
                }
            }

            return true;
        }


    }
}
